<?php


namespace app\api\service;


use app\api\model\Account;
use app\api\model\Click;
use app\api\model\Product;
use app\api\model\Registered;
use app\common\service\getPhoneInfoService;
use app\lib\exception\ServerException;
use Driver\Cache\Redis;

class TimingService
{
    # 获取今天的所有注册数据
    public function updatePhoneMoneyToday()
    {
        $model = new Registered();
        $json = $model->whereTime('add_time','today')
            ->select()
            ->toJson();
        $service = new getPhoneInfoService();
        $result = $service->updatePhoneInfo($json);
        return $result;
    }

    # 获取过去七天的所有注册数据
    public function updatePhoneMoneyLastSevenDay()
    {
        $today = date("Y-m-d",strtotime("today"));
        $lastSevenDay = date("Y-m-d",strtotime("-7 day"));
        $model = new Registered();
        $json = $model->whereTime('add_time',[$lastSevenDay, $today])
            ->select()
            ->toJson();
        $service = new getPhoneInfoService();
        $result = $service->updatePhoneInfo($json);
        return $result;
    }

    # 获取所有的账号并同步到redis
    public function mysqlToRedis()
    {
        try{
            $allAccount = Account::getAllAccount();
            foreach ($allAccount as $list){
                # 缓存每个账户详情到redis 可以通过name和logo获取到redis中的账号详情
                $redis_hash_key_by_name = config('redis.account').$list['name'];
                $redis_hash_key_by_logo = config('redis.logo').$list['logo'];
                Redis::hMset($redis_hash_key_by_name, $list);
                Redis::hMset($redis_hash_key_by_logo, $list);
            }
            return true;
        }catch (\Exception $e){
            return false;
        }
    }

    # 获取今天每个账户
    public function setAccountIps($arr)
    {
        $this->get_account_ip($arr);
        return 'success';
    }

    # 循环所有的数据 获取每个数据的
    private function get_account_ip($arr)
    {
        foreach ($arr as $account){
            $name = $account['name'];
            $redis_set_key = config('redis.ips').$name;
            Redis::DelKey($redis_set_key);
            if(empty($account['pop'])){
                Redis::sAdd($redis_set_key, '127.0.0.1');
            }else{
                $this->pop_ips_to_redis($account, $redis_set_key);
            }
        }
    }

    # 组装每个账户当天的ip集合  并写入到redis_set
    private function pop_ips_to_redis($account, $redis_set_key)
    {
        $ips_arr = [];
        foreach ($account['pop'] as $list){
            array_push($ips_arr, $list['ip']);
        }
        Redis::sAddArr($redis_set_key, $ips_arr);
    }

    # 获取当天每个产品的点击数和申请数
    public function get_product_num()
    {
        $click = $this->get_click_num();
        $open = $this->get_open_num();
        $today = date("Y-m-d",time());
        $add_time = now_time();
        $model = new Click();
        $data = [
            'click_num' => json_encode($click),
            'open_num' => json_encode($open),
            'today' => $today,
            'add_time' => $add_time
        ];
        $model->create($data);
        $this->del_redis_key();
        return ['code'=>200];
    }

    # 对外提供接口
    public function get_click()
    {
        $click = $this->get_click_num();
        $today = date("Y-m-d",time());
        return [
            'click' => $click,
            'today' => $today
        ];
    }

    # 对外提供接口
    public function get_open()
    {
        $open = $this->get_open_num();
        $today = date("Y-m-d",time());
        return [
            'open' => $open,
            'today' => $today
        ];
    }

    # 获取每个id产品对应的点击数，
    private function get_click_num()
    {
        $click_num_set_key = config('redis.click');
        $click_num = Redis::hget($click_num_set_key);
        //$click_num = json_decode("{\"56\":\"28\",\"53\":\"5\",\"59\":\"2\",\"61\":\"2\",\"14\":\"2\",\"58\":\"2\",\"21\":\"1\",\"57\":\"1\",\"27\":\"1\",\"43\":\"2\",\"49\":\"1\",\"62\":\"1\"}", true);
        $arr = $this->get_in_ids_data($click_num);
        return $arr;
    }

    # 获取每个id产品对应的申请数，
    private function get_open_num()
    {
        $open_num_set_key = config('redis.open');
        $get_open = Redis::hget($open_num_set_key);
        //$get_open = json_decode("{\"56\":\"18\",\"53\":\"7\",\"59\":\"2\",\"61\":\"2\",\"27\":\"1\",\"43\":\"3\",\"49\":\"1\"}", true);
        $arr = $this->get_in_ids_data($get_open);
        return $arr;
    }

    # 获取id在区间的产品详情
    private function get_in_ids_data($num)
    {
        $ids = $this->get_ids($num);
        $model = new Product();
        try{
            $result= $model->where('product_id', 'in', $ids)
                ->select()
                ->toArray();
        }catch (\Exception $e){
            throw new ServerException();
        }
        $arr = $this->today_num($result, $num);
        return $arr;
    }

    # 获取每个id对应的产品详情
    private function today_num($data,$num)
    {
        $arr = [];
        foreach ($data as $value){
            $info = ['product_id'=> $value['product_id'], 'title' => $value['title'], 'num' => $num[$value['product_id']]];
            array_push($arr, $info);
        }
        return $arr;
    }

    # 获取产品的id集合
    private function get_ids($num)
    {
        $ids = [];
        foreach ($num as $key=>$value){
            array_push($ids, $key);
        }
        return $ids;
    }

    # 每天统计完成后重置点击数和申请数
    private function del_redis_key()
    {
        Redis::DelKey(config('redis.click'));
        Redis::DelKey(config('redis.open'));
    }
}